/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 2 -*- */
/**
* @file i2c.cpp
* 
* Library for comunication through an I2C bus.
* 
* @author Miguel Ángel Vílchez López 2010 <sacra@openmatica.es>
*
* Codigo is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* 
* Codigo is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
* 
* You should have received a copy of the GNU General Public License along
* with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "i2c.hpp"
#include "debug.cpp"

CMI2c::CMI2c(const char* dev,__u8 address,bool debug=false,const char* filename=""):debug(debug,filename)
{
	this->dev=(char*)malloc((strlen(dev)+1)*sizeof(char));
	strcpy(this->dev,dev);
	this->address=address;
}

CMI2c::~CMI2c()
{}

int CMI2c::sendBlock(__u8* data)
{
	int file=0,size=0;
	size=this->strlen__u8(data);
	int res;
	
	this->debug.debug("Trying to open the device...");
	if ((file = open(this->dev,O_RDWR)) < 0)
	{
		this->debug.error(strerror(errno),__FILE__,__FUNCTION__,(__LINE__));
		return -1;
	}

	//this->debug.debug("Trying to open the address of the device...");
	res = ioctl(file,I2C_SLAVE,this->address);
	if (res < 0)
	{
		this->debug.error(strerror(errno),__FILE__,__FUNCTION__,(__LINE__));
		return -1;
	}

	//this->debug.debug("Trying to send the data to the device...");
	if(i2c_smbus_write_block_data(file,0,size,data) == -1 )
	{
		this->debug.error(strerror(errno),__FILE__,__FUNCTION__,(__LINE__));
		return -1;
	}
	
	close(file);
	return 0;
		
}

int CMI2c::recvWord(char* data,__u8 command)
{
  int file;
  __u16 buf;
  int res;

	//this->debug.debug("Trying to open the device...");
	if ((file = open(this->dev,O_RDWR)) < 0)
	{
		this->debug.error(strerror(errno),__FILE__,__FUNCTION__,(__LINE__));
		return -1;
	}

	//this->debug.debug("Trying to open the address of the device...");
	res = ioctl(file,I2C_SLAVE,this->address);
	if (res < 0)
	{
		this->debug.error(strerror(errno),__FILE__,__FUNCTION__,(__LINE__));
		return -1;
	}
	
	buf=i2c_smbus_read_word_data(file,command);
	sprintf(data,"%u",swap_bytes(buf));

	close(file);

	return 0;

}

int CMI2c::strlen__u8(__u8* data)
{
	int a=0;
	while(data[a]!='\0')
	{	a++; }
	return a;
}

__u16 CMI2c::swap_bytes(__u16 data)
{
	return (data >> 8) | (data << 8);
}
